package com.enzoism.springboot.dive.a2Interrupt;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedInputStreamExample {

    public static void main(String[] args) {
        try {
            PipedInputStream input = new PipedInputStream();
            PipedOutputStream output = new PipedOutputStream();
            input.connect(output); // 连接输入输出流

            // 创建写入线程
            Thread writerThread = new Thread(() -> {
                try {
                    for (int i = 1; i <= 5; i++) {
                        output.write(i); // 写入数据到输出流
                        Thread.sleep(1000); // 模拟写入间隔
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        output.close(); // 关闭输出流
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 创建读取线程
            Thread readerThread = new Thread(() -> {
                try {
                    while (true) {
                        int data = input.read(); // 从输入流读取数据
                        System.out.println("Read data: " + data);
                    }
                } catch (IOException e) {
                    System.out.println("Thread interrupted: " + e.getMessage());
                } finally {
                    try {
                        input.close(); // 关闭输入流
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 启动线程
            writerThread.start();
            readerThread.start();

            // 模拟线程中断
            Thread.sleep(3000); // 模拟中断前等待一段时间
            readerThread.interrupt(); // 中断读取线程

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}